<template>
  <view class="">
    <h1>WebSocket Chat</h1>
    <form @submit="onSubmit">
      <input name="test" v-model="testValue"></input>
      <button form-type="submit">Submit</button>
    </form>
    <view v-for="(item,index) in list" :key="index">
      {{item}}
    </view>
  </view>
</template>

<script>
  import UniSocket from "@/common/socket"

  export default {
    data() {
      return {
        testValue: null,
        list: [],
        socket: null
      }
    },
    onLoad() {},
    onShow() {
      console.log("onShow")
      this.socketInit()
    },
    onHide() {
      console.log("onHide")
      this.socketDestroy()
    },
    onUnload() {
      console.log("onUnload")
      this.socketDestroy()
    },
    methods: {
      socketInit() {
        const token = uni.getStorageSync('token')
        this.socket = new UniSocket({ url: 'ws://1q460596d9.iok.la/ws/guan', 'token': token })
        this.socket.on('test', this.reply);
      },
      socketDestroy() {
        // this.socket.off('test', this.reply)
        this.socket.close()
      },
      reply(data) {
        console.log('reply: ', data);
        let value = "Message text was: " + this.testValue
        if (this.testValue) {
          this.list.push(value)
          this.testValue = null
        }
      },
      onSubmit() {
        this.socket.emit('test', { msg: this.testValue })
      }
    },
  }
</script>

<style>
</style>
